package software.agileCourse2013.KillerGame.biz.Command;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Map;
import java.util.Set;

import org.apache.catalina.websocket.WsOutbound;

import software.agileCourse2013.KillerGame.service.models.UserModel;
import software.agileCourse2013.KillerGame.utils.StringUtil;

/**
 * Command
 * @author lc
 * @create at 2013-4-21
 * 
 */
public abstract class TemplateCommand implements JsonParameter,JsonResult{
	protected Map<Integer, UserModel> userMap;
	
	/**
	 * 根据Json参数执行命令
	 * @param paras
	 * Json参数
	 * @param user
	 * 用户参数
	 * @return
	 * JsonResult
	 */
	protected abstract JsonResult run(JsonParameter paras,UserModel user) ;
	
	
	/**
	 * 将json字符串参数解析并执行最后转为json结果字符串
	 * @param arg
	 * json字符串参数
	 * @param user
	 * 用户参数
	 * @param userMap
	 * 用户组信息
	 */
	public  void execute(String arg,UserModel user,Map<Integer, UserModel> userMap){
		this.userMap = userMap;
		if (!StringUtil.isBlank(arg)) {
			 broadcast(toJson(run(analysisParas(arg), user))) ;
		}
	}
	
	/**
	 * 默认发送方式为给userMap中每个人都发送(可重写)
	 * @param jsonMsg
	 * 返回的json数据
	 */
	protected void broadcast(String jsonMsg) {
	      Set<Integer> set = userMap.keySet();
	      for (Integer integer : set) {
	        UserModel user = (UserModel)userMap.get(integer);
	        WsOutbound outbound = user.getOutBound();
	        CharBuffer buffer = CharBuffer.wrap(jsonMsg);
	        try {
	                  outbound.writeTextMessage(buffer);
	          outbound.flush();
	        } catch (IOException e) {
	          e.printStackTrace();
	        }
	      }
	    }
}
